package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.example.library_common.adapter.JssBaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.album.utils.Utils
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.PixUtils
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AreaItemBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.CITY
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.COMMUNITY
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.DISTRICT
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.PROVINCE
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.LocationBean
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import com.google.android.material.tabs.TabLayout
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.interfaces.OnSelectListener

class SelectLocationPop(context: Context) : BottomPopupView(context), OnItemClickListener,
    TabLayout.OnTabSelectedListener {

    companion object {
        const val RAW_JSON = 100
    }

    override fun getPopupHeight(): Int {
        return PixUtils.dp2px(380)
    }


    private var isAfterDistrict = false

    fun setIsAfterDistrict(isAfterDistrict: Boolean): SelectLocationPop {
        this.isAfterDistrict = isAfterDistrict

        return this
    }

    private lateinit var mTabLayout: TabLayout

    private lateinit var mRecyclerView: RecyclerView

    private lateinit var mAdapter: JssBaseQuickAdapter<AreaItemBean>

    private lateinit var mProgressBar: ProgressBar

    private lateinit var sureTv: TextView

    private val mData = mutableListOf<AreaItemBean>()

    private val mAreaTypeTransfer = mutableMapOf(
        "$PROVINCE" to "$CITY",
        "$CITY" to "$DISTRICT",
        "$DISTRICT" to ""
    )

    private var selectedItem: AreaItemBean? = null

    private var resTv: TextView? = null


    private var onSelectListener: OnSelectListener? = null

    fun setOnSelectListener(onSelectListener: OnSelectListener): SelectLocationPop {
        this.onSelectListener = onSelectListener
        return this
    }


    override fun getImplLayoutId() = R.layout.select_location_pop

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    @SuppressLint("RestrictedApi")
    override fun onCreate() {
        super.onCreate()

        if (isAfterDistrict){
            mAreaTypeTransfer["$DISTRICT"]="$COMMUNITY"
        }

        mTabLayout = findViewById(R.id.mTabLayout)
        mProgressBar = findViewById(R.id.mProgressBar)
        sureTv = findViewById(R.id.sureTv)
        resTv = findViewById(R.id.resTv)

        sureTv.setOnClickListener {
            val addresses = addresses()
            if (addresses.isEmpty()) {
                Toast.makeText(context, "请选择具体地址", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            onSelectListener?.onSelected(addresses)

            dismiss()

        }

        mRecyclerView = findViewById(R.id.mRecyclerView)
        mRecyclerView.setHasFixedSize(true)
        mRecyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        mAdapter =
            object : JssBaseQuickAdapter<AreaItemBean>(R.layout.select_location_item_pop, mData) {

                override fun convert(holder: JssBaseViewHolder?, item: AreaItemBean?) {
                    super.convert(holder, item)
                    val textColor = if (selectedItem?.areaName == (item?.areaName
                            ?: "textColor")
                    ) R.color.PrimaryColor else R.color.blackAlpha55

                    holder?.setText(R.id.textTv, item?.areaName)
                        ?.setTextColorRes(R.id.textTv, textColor)
                }

            }
        mRecyclerView.adapter = mAdapter

        mProgressBar.visibility = VISIBLE

        mAdapter.setOnItemClickListener(this)

        mTabLayout.addOnTabSelectedListener(this)


        getLocation("$PROVINCE")

    }

    private fun getLocation(areaType: String?) {
        resTv?.visibility = GONE

        mProgressBar.visibility = VISIBLE

        sureTv.visibility = GONE

        val areaTypeStr = selectedItem?.areaType.toString()

        if (areaTypeStr != areaType) {
            selectedItem = getArea(areaType, selectedItem)
        }

        when (areaType) {
            "$PROVINCE" -> {
                getProvince()
            }

            "$CITY" -> {
                getCity()
            }

            "$DISTRICT" -> {
                getDistrict()
            }

            "$COMMUNITY"->{
                getCommunity()
            }

            else -> {
                mProgressBar.visibility = GONE

                sureTv.visibility = VISIBLE

                mAdapter.notifyDataSetChanged()
            }
        }

    }

    private fun getCommunity() {
        val paid = if (selectedItem?.areaType == COMMUNITY)
            selectedItem?.parentArea?.aid
        else
            selectedItem?.aid
        RestClient.builder()
            .url(R.string.queryAreaListByParams)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "areaType" to "$COMMUNITY",
                        "paid" to "$paid"
                    )
                )
            )
            .success { parseCommunityDate(it) }
            .failure {
                onFailed("获取失败")
            }
            .error { _, msg ->
                onFailed(msg)
            }.build().post()
    }

    private fun parseCommunityDate(data: String?) {
        mProgressBar.visibility = GONE

        sureTv.visibility = VISIBLE

        val obj = JSON.parseObject(data)
        val proList = obj["proList"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(proList), AreaItemBean::class.java)
        for (e in array) {
            e.areaType = COMMUNITY
        }
        loadListDate(array)
    }

    private fun getArea(areaType: String?, currentArea: AreaItemBean?): AreaItemBean? {
        var areaItemBean: AreaItemBean? = null

        val parentArea = currentArea?.parentArea

        val areaTypeStr = parentArea?.areaType.toString()

        if (parentArea != null) {

            areaItemBean = if (areaTypeStr == areaType) {
                parentArea
            } else {
                getArea(areaType, parentArea)
            }
        }
        return if (areaTypeStr == areaType) areaItemBean else currentArea
    }


    private fun getDistrict() {


        val paid = if (selectedItem?.areaType == DISTRICT)
            selectedItem?.parentArea?.aid
        else
            selectedItem?.aid

        RestClient.builder()
            .url(R.string.queryAreaListByParams)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "areaType" to "$DISTRICT",
                        "paid" to "$paid"
                    )
                )
            )
            .success { parseDistrictDate(it) }
            .failure {
                onFailed("获取失败")
            }
            .error { _, msg ->
                onFailed(msg)
            }.build().post()
    }

    private fun getCity() {
        val paid = if (selectedItem?.areaType == CITY)
            selectedItem?.parentArea?.aid
        else
            selectedItem?.aid


        RestClient.builder()
            .url(R.string.queryAreaListByParams)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "areaType" to "$CITY",
                        "paid" to "$paid"
                    )
                )
            )
            .success { parseCityDate(it) }
            .failure {
                onFailed("获取失败")
            }
            .error { _, msg ->
                onFailed(msg)
            }.build().post()
    }

    private fun getProvince() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        RestClient.builder()
            .url(R.string.applyProxyPre)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "deviceToken" to "$deviceTokens",
                        "uid" to "${userInfo?.uid}"
                    )
                )
            )
            .success {
                parseProvinceDate(it)
            }.failure { onFailed("获取失败") }
            .error { _, msg -> onFailed(msg) }
            .build().post()
    }


    private fun parseDistrictDate(data: String?) {

        mProgressBar.visibility = GONE

        sureTv.visibility = VISIBLE

        val obj = JSON.parseObject(data)
        val proList = obj["proList"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(proList), AreaItemBean::class.java)
        for (e in array) {
            e.areaType = DISTRICT
        }
        loadListDate(array)
    }

    private fun parseCityDate(data: String?) {

        mProgressBar.visibility = GONE

        sureTv.visibility = VISIBLE

        val obj = JSON.parseObject(data)
        val proList = obj["proList"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(proList), AreaItemBean::class.java)
        for (e in array) {
            e.areaType = CITY
        }
        loadListDate(array)
    }

    private fun onFailed(msg: String?) {
        if (selectedItem?.areaType != DISTRICT) {
            resTv?.text = msg
            resTv?.visibility = VISIBLE
        }

    }

    private fun parseProvinceDate(data: String?) {

        mProgressBar.visibility = GONE

        sureTv.visibility = VISIBLE

        val obj = JSON.parseObject(data)
        val proList = obj["proList"] ?: ""

        val array = JSON.parseArray(JSON.toJSONString(proList), AreaItemBean::class.java)
        for (e in array) {
            e.areaType = PROVINCE
        }
        loadListDate(array)
    }

    private fun loadListDate(array: List<AreaItemBean>) {
        mAdapter.clears()
        mAdapter.addData(array)
        if (mAdapter.data.size <= 0) {
            onFailed("暂无数据")
        }
    }


    private fun addresses(): List<AreaItemBean?> {
//        return getAreaName(selectedItem)

        val ls = mutableListOf<AreaItemBean?>()
        getAreaList(selectedItem, ls)
        ls.reverse()
        return ls
    }

    private fun getAreaList(
        selectedItem: AreaItemBean?,
        ls: MutableList<AreaItemBean?>
    ): List<AreaItemBean?> {
        if (selectedItem != null) {
            ls.add(selectedItem)
        }

        if (selectedItem?.parentArea != null) {
            getAreaList(selectedItem.parentArea, ls)
        }

        return ls
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

        val item = mAdapter.getItem(position)

        if (selectedItem?.areaType == item.areaType) {

            item.parentArea = selectedItem?.parentArea

        } else {
            item.parentArea = selectedItem
        }

        selectedItem = item

        var tabIndex = -100
        for (index in 0 until mTabLayout.tabCount) {
            val tab = mTabLayout.getTabAt(index)

            if (tab?.tag?.toString() == item.areaType.toString()) {
                tabIndex = index
                break
            }
        }

        if (tabIndex >= 0) {

            val tabAt = mTabLayout.getTabAt(tabIndex)

            mTabLayout.selectTab(tabAt, true)

            tabAt?.text = item.areaName

        } else {
            mTabLayout.addTab(
                mTabLayout.newTab()
                    .setText(item.areaName)
                    .setTag(item.areaType.toString()),
                true
            )
        }

    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        Log.d("onTab", "onTabSelected: ")
        val lastTabIndex = mTabLayout.tabCount - 1

        val remove = mTabLayout.tabCount - 1 - (tab?.position ?: lastTabIndex)

        for (index in 0 until remove) {
            mTabLayout.removeTabAt(mTabLayout.tabCount - 1)
        }

        val text = tab?.text ?: ""

        if (text.isEmpty()) {
            return
        }

        var areaTypeStr: String? = selectedItem?.areaType.toString()
        areaTypeStr =
            if (areaTypeStr != tab?.tag)
                tab?.tag.toString()
            else
                mAreaTypeTransfer[areaTypeStr]

        getLocation(areaTypeStr)


    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {

    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
        Log.d("onTab", "onTabReselected: ")

        var areaTypeStr: String? = selectedItem?.areaType.toString()

        areaTypeStr =
            if (areaTypeStr == tab?.tag
                && mAdapter.data.size > 0
            )
                mAreaTypeTransfer[areaTypeStr]
            else
                tab?.tag.toString()

        getLocation(areaTypeStr)

    }

    override fun dismiss() {
        super.dismiss()
        onSelectListener = null
    }

    override fun onDismiss() {
        super.onDismiss()
        mTabLayout.removeOnTabSelectedListener(this)
    }

    interface OnSelectListener {
        fun onSelected(ls: List<AreaItemBean?>)
    }

}